<template>
  <view class="group-charging">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="组团充电"></van-nav-bar>
    <!-- #endif -->
    <view :class="['list', state ? '' : 'list-nobnt']" :style="heightScroll">
      <view class="list-bg" :style="{ backgroundImage: `url(${data.pic})` }">
        <view v-if="userId" class="list-history" @tap.stop="toGroupHistory">参团历史</view>
      </view>
      <view class="content">
        <view class="title">
          <view class="title-icon"></view>
          <view class="title-des">组团规则</view>
        </view>
        <view class="des">
          {{ data.des }}
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-wrap" v-if="state">
      <button class="bnt-wrap bnt" @tap="handleClick">
        {{ data.btnText }}
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import {
  getUserId,
  getToken,
  setUserId,
  setToken,
  systemInfo,
  getwv,
  setToastInstance,
} from '@/mixins/info';
import {
  getActivityById,
  buildTeamCheck,
  buildTeam,
  joinTeam,
  joinTeamCheck,
} from '@/service/apis/market';
import { loginCheck } from '@/service/apis/login';
import { uniLogin } from '@/utils/api';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const $toast: any = inject('$Toast');

const heightScroll = computed(() => {
  if (state) {
    // #ifdef H5
    return `height:${
      systemInfo.screenHeight - systemInfo.navHeight - systemInfo.safeBottom - getwv(62)
    }px`;
    // #endif
    return `height:${systemInfo.screenHeight - systemInfo.safeBottom - getwv(62)}px`;
  }
  // #ifdef H5
  return `height:${systemInfo.screenHeight - systemInfo.navHeight - systemInfo.safeBottom}px`;
  // #endif
  return `height:${systemInfo.screenHeight - systemInfo.safeBottom}px`;
});

let userId = ref(getUserId());

const data = reactive({
  id: '',
  pic: '',
  des: '',
  checkCode: '', //100:去开团 101:查看成团进展 200:无团队加入 201:有团队加入(且是该活动下的团队) 202:有团队加入(不是该活动下的团队)
  teamId: '',
  btnText: '',
  status: '',
  requestFlag: false,
});

const state = computed(() => {
  if (['1', '2', '3'].includes(data.status)) {
    return true;
  }
  return false;
});

// 去开团/查看成团进展
const handleClick = () => {
  switch (data.status) {
    case '1':
      buildTeam(data.id).then((res: any) => {
        data.teamId = res;
        uni.navigateTo({
          url: `/pagesMain/groupCharging/groupChargingProgress?id=${res}`,
          success: () => {
            data.status = '2';
            data.btnText = '查看成团进展';
          },
        });
      });
      break;
    case '2':
      uni.navigateTo({
        url: `/pagesMain/groupCharging/groupChargingProgress?id=${data.teamId}`,
      });
      break;
    case '3':
      joinTeam(data.teamId).then((result: any) => {
        if (result) {
          if (result.code === '204') {
            $toast(result.msg);
            data.btnText = '开新团';
            data.status = '1';
          }
        } else {
          uni.navigateTo({
            url: `/pagesMain/groupCharging/groupChargingProgress?id=${data.teamId}`,
            success: () => {
              data.status = '2';
            },
          });
        }
      });
      break;
  }
};

const toGroupHistory = () => {
  uni.navigateTo({
    url: `/pagesMain/groupCharging/groupHistory`,
  });
};

// 初始化
const getActivityDetail = () => {
  getActivityById(data.id).then((res: any) => {
    data.pic = res.pic;
    data.des = res.rule;
  });
};

// 组团充电活动开团校验
const buildTeamCheckMethod = () => {
  buildTeamCheck(data.id)
    .then((res: any) => {
      // 100:去开团 101:查看成团进展
      if (res) {
        data.checkCode = res.code;
        if (res.code === '101') {
          data.btnText = '查看成团进展';
          data.teamId = res.msg;
          data.status = '2';
        } else {
          data.status = '1';
          data.btnText = '开新团';
        }
      } else {
        data.btnText = '开新团';
        data.status = '1';
      }
    })
    .catch(() => {
      data.btnText = '开新团';
      data.status = '1';
    });
};

// 参加组团充电活动入团校验
const joinTeamCheckMethod = () => {
  joinTeamCheck(data.teamId)
    .then((res: any) => {
      // 200:无团队加入 取消:去开团 id:无
      // 201:有团队加入(且是该活动下的团队) 取消:查看成团进展 id:所属团ID
      // 202:有团队加入(不是该活动下的团队) 取消:去开团 id:无
      // 203:已是当前团队成员 查看成团进展 id:无
      // 204:当前团队已满 去开团 id:无
      // 205:已是其他团队团长(且是该活动下的团队) 查看成团进展 id:所属团ID
      // 206:已是其他团队团长(不是该活动下的团队) 去开团 id:无

      if (res) {
        data.checkCode = res.code;
        if (res.code === '200') {
          uni.showModal({
            content: res.msg,
            success: (e: any) => {
              if (e.confirm) {
                // 同意————加入带进来的teamId
                data.btnText = '查看成团进展';
                joinTeam(data.teamId)
                  .then((result: any) => {
                    if (result) {
                      if (result.code === '204') {
                        $toast(result.msg);
                        data.btnText = '开新团';
                        data.status = '1';
                      }
                    } else {
                      data.status = '2';
                      uni.navigateTo({
                        url: `/pagesMain/groupCharging/groupChargingProgress?id=${data.teamId}`,
                      });
                    }
                  })
                  .catch(() => {
                    data.status = '3';
                  });
              } else {
                // 拒绝————去开团
                data.btnText = '开新团';
                data.status = '1';
              }
            },
          });
        } else if (['201', '202'].includes(res.code)) {
          uni.showModal({
            content: '您有已参加团队，接受邀请后原有团队贡献不会代入新团队，是否继续？',
            success: (e: any) => {
              if (e.confirm) {
                // 同意————加入带进来的teamId
                data.btnText = '查看成团进展';
                joinTeam(data.teamId)
                  .then((result: any) => {
                    if (result) {
                      if (result.code === '204') {
                        $toast(result.msg);
                        data.btnText = '开新团';
                        data.status = '1';
                      }
                    } else {
                      data.status = '2';
                      uni.navigateTo({
                        url: `/pagesMain/groupCharging/groupChargingProgress?id=${data.teamId}`,
                      });
                    }
                  })
                  .catch(() => {
                    data.status = '3';
                  });
              } else {
                // 拒绝————用接口返回的teamId
                if (res.code === '202') {
                  data.status = '1';
                  data.btnText = '开新团';
                } else {
                  data.teamId = res.id;
                  data.status = '2';
                  data.btnText = '查看成团进展';
                }
              }
            },
          });
        } else if (['203', '205'].includes(res.code)) {
          $toast(res.msg);
          if (res.code === '205') {
            data.teamId = res.id;
          }
          data.status = '2';
          data.btnText = '查看成团进展';
        } else if (['204', '206'].includes(res.code)) {
          $toast(res.msg);
          data.status = '1';
          data.btnText = '开新团';
        }
      } else {
        data.btnText = '开新团';
        data.status = '1';
      }
    })
    .catch(() => {
      data.btnText = '开新团';
      data.status = '1';
    });
};

const flagLogin = async () => {
  // 判断是否有token
  userId.value = getUserId();
  if (userId.value) {
    const code = await uniLogin('weixin');
    loginCheck(
      {
        token: getToken(),
        userId: userId.value,
        jsCode: code,
      },
      true
    )
      .then((res: any) => {
        if (res) {
          if (data.teamId) {
            joinTeamCheckMethod();
          } else {
            buildTeamCheckMethod();
          }
        }
      })
      .catch(() => {
        setUserId('');
        setToken('');
        loginModal();
      });
  } else {
    loginModal();
  }
};

const loginModal = () => {
  uni.showModal({
    content: '活动仅限平台用户参加，您尚未登录，是否前往登录？',
    success: (e: any) => {
      if (e.confirm) {
        data.requestFlag = true;
        uni.navigateTo({
          url: `/pages/login/login?page=/pagesMain/groupCharging/groupCharging?id=${data.id}&teamId=${data.teamId}`,
        });
      }
    },
  });
};

// 场景展示按钮罗列
// A、不展示按钮
// 1、非活动期间（已结束、未开始）
// 2、用户未登录
// 3、用户无权限参加当前活动

// B、展示“查看成团进展”
// 1、用户当前活动无进行中团，接受邀请加入新团
// 2、用户当前活动有进行中团，接受/拒绝邀请入团
// 3、用户是团长，不能接受成团邀请
// 4、用户从广告入口进入，当前活动有进行中的团
// 5、用户已在当前团中，重复接受邀请

// C、展示“开新团”
// 1、用户当前活动无进行中团，拒绝邀请
// 2、用户从广告入口进入，当前活动无进行中的团
// 3、用户在其他活动有进行中的团
// 4、接受邀请，团员已满无法加入

onLoad((option: any) => {
  data.id = option.id;
  data.teamId = option.teamId;
  getActivityDetail();
  flagLogin();
});

onShow(() => {
  if (data.requestFlag) {
    userId.value = getUserId();
    if (userId.value) {
      data.requestFlag = false;
      if (data.teamId) {
        joinTeamCheckMethod();
      } else {
        buildTeamCheckMethod();
      }
    }
  }
});

// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
.group-charging {
  width: 100vw;
  height: 100%;
  position: absolute;
  top: 0;
  box-sizing: border-box;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);
  background-color: #f2f2f2;
  .list {
    position: relative;
    height: calc(100% - 62px - constant(safe-area-inset-bottom));
    height: calc(100% - 62px - env(safe-area-inset-bottom));
    overflow-y: scroll;
    background-color: #f2f2f2;
    &-bg {
      width: 100%;
      height: 205px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }
    &-history {
      box-sizing: border-box;
      position: absolute;
      top: 9px;
      right: 9px;
      width: 65px;
      height: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 67px;
      border: 1px solid #fff;
      background: #365ae2;
      color: #fff;
      font-size: 11px;
      line-height: 18px;
    }
    .content {
      margin: 12px 9px;
      box-sizing: border-box;
      width: 357px;
      padding: 16px;
      border-radius: 8px;
      background: #fff;
      .title {
        margin-bottom: 6px;
        display: flex;
        align-items: center;
        &-icon {
          margin: 0 8px 0 2px;
          box-sizing: border-box;
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background-image: url($url + 'group/book.png');
          background-size: 10px 10px;
          background-position: center center;
          background-repeat: no-repeat;
          background-color: #242424;
        }
        &-des {
          color: #000000;
          font-size: 16px;
          font-weight: 600;
          line-height: 24px;
        }
      }
      .des {
        white-space: pre-wrap;
        color: #858585;
        text-align: justify;
        font-size: 14px;
        line-height: 21px;
      }
    }
  }
  .list-nobnt {
    height: 100%;
  }

  .bottom-wrap {
    position: absolute;
    display: flex;
    justify-content: space-between;
    bottom: 0;
    width: 100vw;
    height: 62px;
    padding: 0 16px;
    box-sizing: border-box;
    background-color: #ffffff;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
    border-top: 1px solid #e6e6e6;

    .bnt {
      width: 100%;
      height: 40px;
      margin-top: 12px;
      border-radius: 50px;
      font-size: 16px;
    }
  }
}
</style>